import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
//封装一个函数，用于判断是否还有相关权限
function hasUrl(url:string,next:Function){
  let result =JSON.parse((sessionStorage.getItem('userinfo')+'')).menus_url.some((item:any)=>url==item.url)
  if(result){
    next()
  }else{
    next('/home')
  }
}

const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    component: () => import('../pages/login.vue')
  },
  {
    path: '/index',
    component: () => import('../pages/index.vue'),
    children: [
      {
        path:'/home',
        component: () => import('../views/home.vue')
      },
      {
        path: '/menu',
        component: () => import('../views/menu/menu.vue'),
        beforeEnter: (to, from, next) => {
          hasUrl('/menu',next)
        }
      },
      {
        path: '/role',
        component: () => import('../views/role/role.vue'),
        name: '角色管理',
        beforeEnter: (to, from, next) => {
          hasUrl('/role',next)
        }
      },
      {
        path: '/user',
        component: () => import('../views/user/user.vue'),
        name: '管理员管理',
        beforeEnter: (to, from, next) => {
          hasUrl('/user',next)
        }
      },
      {
        path:'',
        redirect:'/home'
      }
    ]
  },{
    path:'',
    redirect:'/index'
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

//全局登录拦截
router.beforeEach((to,from,next)=>{
  if(to.path=='/login'){
    next()
    return
  }
  if(sessionStorage.getItem('userinfo')){
    next()
    return
  }
  next('/login')
})

export default router

// interface People {
//   name:string,
//   age:number
// }

// var people:People = {
// name:'777',
// age:999,
// sex:'nv'
// }

